from rest_framework.views import APIView
from rest_framework.response import Response
from rest_framework import status
from django.shortcuts import get_object_or_404
from rbac.models import WorkFlowModel, WorkFlowPermissionModel, WorkFlowApprovalModel, RoleModel, PositionModel
from rbac.serial import WorkFlowSerializer, RoleSerializer, PositionSerializer


class WorkFlowAPIView(APIView):
    """
    添加和获取工作流列表
    """

    def get(self, request):
        workflows = WorkFlowModel.objects.all()
        serializer = WorkFlowSerializer(workflows, many=True)
        return Response(serializer.data, status=status.HTTP_200_OK)

    def post(self, request):
        serializer = WorkFlowSerializer(data=request.data)
        if serializer.is_valid():
            serializer.save()
            return Response({"message": "工作流添加成功"}, status=status.HTTP_201_CREATED)
        return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)


    def delete(self, request):
        workflow_id = request.query_params.get('workflow_id')
        print(workflow_id)
        try:
            workflow = WorkFlowModel.objects.get(id=workflow_id)
            workflow.delete()
            return Response({'message': '工作流删除成功'}, status=status.HTTP_200_OK)
        except WorkFlowModel.DoesNotExist:
            return Response({'message': '工作流不存在'}, status=status.HTTP_404_NOT_FOUND)

class WorkFlowStatusUpdateAPIView(APIView):
    """
    更新工作流状态
    """

    def put(self, request, workflow_id):
        workflow = get_object_or_404(WorkFlowModel, id=workflow_id)
        new_status = request.data.get("status")

        # 验证状态值是否合法
        if new_status not in [0, 1]:
            return Response(
                {"error": "Invalid status value. Status must be 0 (inactive) or 1 (active)."},
                status=status.HTTP_400_BAD_REQUEST,
            )

        workflow.status = new_status
        workflow.save()

        return Response({"message": "Workflow status updated successfully"}, status=status.HTTP_200_OK)



class WorkFlowDetailAPIView(APIView):
    """
    更新或删除单个工作流
    """

    def get_object(self, workflow_id):
        return get_object_or_404(WorkFlowModel, id=workflow_id)

    def put(self, request, workflow_id):
        workflow = self.get_object(workflow_id)
        serializer = WorkFlowSerializer(workflow, data=request.data, partial=True)
        if serializer.is_valid():
            serializer.save()
            return Response({"message": "工作流更新成功"}, status=status.HTTP_200_OK)
        return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)

    def delete(self, request, workflow_id):
        workflow = self.get_object(workflow_id)
        workflow.delete()
        return Response({"message": "工作流删除成功"}, status=status.HTTP_204_NO_CONTENT)


class WorkFlowPermissionAPIView(APIView):
    """
    配置工作流权限
    """

    def post(self, request):
        workflow_id = request.data.get('workflow_id')
        role_ids = request.data.get('roles', [])

        workflow = get_object_or_404(WorkFlowModel, id=workflow_id)

        # 删除旧的权限配置
        WorkFlowPermissionModel.objects.filter(workflow=workflow).delete()

        # 添加新的权限配置
        for role_id in role_ids:
            role = get_object_or_404(RoleModel, id=role_id)
            WorkFlowPermissionModel.objects.create(role=role, workflow=workflow)

        return Response({"message": "权限配置成功"}, status=status.HTTP_200_OK)


class WorkFlowApprovalAPIView(APIView):
    """
    配置工作流审批
    """

    def post(self, request):
        workflow_id = request.data.get('workflow_id')
        approvals = request.data.get('approvals', [])

        workflow = get_object_or_404(WorkFlowModel, id=workflow_id)

        # 删除旧的审批配置
        print(WorkFlowApprovalModel.objects.filter(workflow=workflow),3333333333333333333333333333333)
        print(list(WorkFlowApprovalModel.objects.filter(workflow=workflow)),11111111111111111111111111111111111)
        WorkFlowApprovalModel.objects.filter(workflow=workflow).delete()

        # 添加新的审批配置
        for approval in approvals:
            position_id = approval.get('position_id')
            level = approval.get('level')
            position = get_object_or_404(PositionModel, id=position_id)
            WorkFlowApprovalModel.objects.create(workflow=workflow, position=position, level=level)

        return Response({"message": "审批配置成功"}, status=status.HTTP_200_OK)



# 职务表
class PositionAPIView(APIView):
    """
    添加和获取职务列表
    """

    def get(self, request):
        positions = PositionModel.objects.all()
        serializer = PositionSerializer(positions, many=True)
        return Response(serializer.data, status=status.HTTP_200_OK)

    def post(self, request):
        serializer = PositionSerializer(data=request.data)
        if serializer.is_valid():
            serializer.save()
            return Response({"message": "职务添加成功"}, status=status.HTTP_201_CREATED)
        return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)


class PositionDetailAPIView(APIView):
    """
    展示
    """

    def get_object(self,request):
        position = PositionModel.objects.all()
        ser = PositionSerializer(position, many=True)
        if ser.is_valid():
            return Response(ser.data, status=status.HTTP_200_OK)




